package com.rjs.rpc.invoke;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.reflect.MethodUtils;

public class ProviderReflect {

	private static final ExecutorService executorService = Executors.newCachedThreadPool();
	
	public static void provider(final Object service, int port) throws Exception {
		@SuppressWarnings("resource")
		//每个服务都会占用一个新的端口。。。
		ServerSocket serverSocket = new ServerSocket(port);
		while(true) {
			final Socket socket = serverSocket.accept();
			executorService.execute(new Runnable() {
				public void run() {
					ObjectInputStream inputStream = null;
					ObjectOutputStream outputStream = null;
					try {
						inputStream = new ObjectInputStream(socket.getInputStream());
						String methodName = inputStream.readUTF();
						Object[] arguments = (Object[])inputStream.readObject();
						try {
							outputStream = new ObjectOutputStream(socket.getOutputStream());
							Object result = MethodUtils.invokeExactMethod(service, methodName, arguments);
							outputStream.writeObject(result);
						} catch (Throwable t) {
							outputStream.writeObject(t);
						} finally {
							if (outputStream != null) {
								outputStream.close();
							}
							if (inputStream != null) {
								inputStream.close();
							}
							socket.close();
						}
					} catch (Exception e) {
						e.printStackTrace();
					} 
				}
			});
		}
	}
}
